package com.shensi.adminCollect.service.station.impl;

import com.github.pagehelper.PageHelper;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.exception.BaseException;
import com.shensi.common.core.exception.CustomException;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.enums.station.MarketActivityType;
import com.shensi.adminCollect.mapper.station.CommodityMapper;
import com.shensi.adminCollect.service.station.*;
import com.shensi.adminCollect.utils.station.CodeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * (Commodity)表服务实现类
 *
 * @author makejava
 * @since 2023-08-15 14:11:35
 */
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityMapper commodityMapper;

    @Autowired
    private INonOilCategoryService nonOilCategoryService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private ActivityCommodityRulesService activityCommodityRulesService;

    /**
     * 通过ID查询单条数据
     *
     * @param commodityId 主键
     * @return 实例对象
     */
    @Override
    public Commodity queryById(Long commodityId) {
        return commodityMapper.queryById(commodityId);
    }

    /**
     * 分页查询
     *
     * @param commodity 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Commodity> queryByPage(Commodity commodity, PageRequest pageRequest) {
        long total = this.commodityMapper.count(commodity);
        return new PageImpl<>(this.commodityMapper.queryAllByLimit(commodity, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity insert(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setCreateUser(currentUser.getUser().getUserId());
        commodity.setCreateTime(new Date());
        commodityMapper.insert(commodity);
        return commodity;
    }

    @Override
    public void insertCommodity(List<Commodity> commodityList) {
        // 参数校验
        for (Commodity commodity : commodityList) {
            Commodity newCommodity = new Commodity();
            newCommodity.setStationId(commodity.getStationId());
            newCommodity.setBarCode(commodity.getBarCode());
            Commodity com = commodityMapper.selectCommodity(newCommodity);
            if(Objects.nonNull(com)){
                throw new CustomException("商品已存在");
            }
        }
        for (Commodity commodity : commodityList) {
            synchronized (this) {
                String code = CodeUtil.createCode();
                commodity.setCommodityCode(code);
                commodity.setUpdateTime(new Date());
                insert(commodity);
            }
        }
    }

    /**
     * 修改数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public int update(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setUpdateTime(new Date());
        commodity.setUpdateUser(currentUser.getUser().getUserId());
        int i = commodityMapper.update(commodity);
        return i;
    }

    /**
     * 通过主键删除数据
     *
     * @param commodityId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long commodityId) {
        return commodityMapper.deleteById(commodityId) > 0;
    }

    @Override
    public int delete(List<Long> ids) {
        if(ids!=null&&ids.size()>0){
            return commodityMapper.deleteByIds(ids);
        }
        return 0;
    }

    @Override
    public List<Commodity> query(Commodity commodity) {
        Long categoryId = commodity.getCategoryId();
        if(categoryId!=null){
            List<Long> childIds = nonOilCategoryService.getChildIds(categoryId);
            childIds.add(categoryId);
            commodity.setCategoryIds(childIds);
        }
        PageHelper.startPage(commodity.getPageNum(), commodity.getPageSize(), commodity.getOrderBy());
        List<Commodity> querys = commodityMapper.query(commodity);
        PageHelper.clearPage();
        for (Commodity query : querys) {
            NonOilCategory nonOilCategory = nonOilCategoryService.queryById(query.getCategoryId());
            if(Objects.nonNull(nonOilCategory)) {
                query.setCategoryName(nonOilCategory.getCategoryName());
            }
            Supplier req = new Supplier();
            req.setSupplierId(query.getSupplierId());
            Supplier supplier = supplierService.selectOneSupplier(req);
            if(Objects.nonNull(supplier)){
                query.setSupplierName(supplier.getSupplierName());
            }
        }
        return querys;
    }

    @Override
    public List<Commodity> selectCommodityList(Commodity commodity) {
        List<Commodity> commodityList = commodityMapper.selectCommodityList(commodity);
        for (Commodity com : commodityList) {
            NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
            if(Objects.nonNull(nonOilCategory)) {
                com.setCategoryName(nonOilCategory.getCategoryName());
            }
        }
        return commodityList;
    }

    @Override
    public Commodity queryCommodity(Commodity commodity) {
        Commodity com = commodityMapper.selectCommodity(commodity);
        if(Objects.isNull(com)){
            throw new BaseException("商品不存在");
        }
        NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
        if(Objects.nonNull(nonOilCategory)) {
            com.setCategoryName(nonOilCategory.getCategoryName());
        }
        return com;
    }

    @Override
    public Commodity externalQueryCommodity(Commodity commodity) {
        Commodity com = commodityMapper.selectCommodity(commodity);
        if(Objects.isNull(com)){
            throw new BaseException("商品不存在");
        }
        NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
        if(Objects.nonNull(nonOilCategory)) {
            com.setCategoryName(nonOilCategory.getCategoryName());
        }
        // 计算商品优惠价格
        calculateDiscountPrice(com);
        return com;
    }

    // 计算商品优惠价格
    private void calculateDiscountPrice(Commodity commodity){
        // 获取当前门店的活动
        List<MarketActivity> marketActivities = marketActivityService.progressMarketActivityList(commodity);
        if(CollectionUtils.isEmpty(marketActivities)){
            commodity.setDiscountPrice(commodity.getSalePrice());
            return;
        }

        // 更具活动和商品 匹配优惠规则
        ActivityCommodityRules rules = activityCommodityRulesService.selectCommodityDiscount(commodity, marketActivities);
        if(Objects.isNull(rules) || Objects.isNull(rules.getCommodityId())){
            commodity.setDiscountPrice(commodity.getSalePrice());
            return;
        }
        // 计算优惠价格
        if(MarketActivityType.DISCOUNT_NUM.getValue().equals(rules.getMarketActivityType())){
            // 打折 计算商品优惠价格 四舍五入 保留2位小数
            BigDecimal discountPrice = commodity.getSalePrice().subtract(commodity.getSalePrice()
                    .multiply(BigDecimal.valueOf(rules.getDiscountNum()/100))
                    .setScale(2, RoundingMode.HALF_UP));
            commodity.setDiscountPrice(discountPrice);
        }
        if(MarketActivityType.SPECIAL_PRICE.getValue().equals(rules.getMarketActivityType())){
            // 特价 计算商品优惠价格
            commodity.setDiscountPrice(rules.getSpecialPrice());
        }
    }

    @Override
    public List<Long> getSupplierIdList(Commodity commodity) {
        return commodityMapper.getSupplierIdList(commodity);
    }
}
